import {
	defineConfig,
	loadEnv
} from "vite";
import path from 'path'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import {
	createSvgIconsPlugin
} from 'vite-plugin-svg-icons'
import Components from 'unplugin-vue-components/vite'
import {
	ElementPlusResolver
} from 'unplugin-vue-components/resolvers'
import ElementPlus from 'unplugin-element-plus/vite'
const buildIndex = () => {
	return {
		name: 'html-transform',
		transformIndexHtml(html) {
			return html.replace(/@VERSION@/g, require('./package.json').version)
		}
	}
}
export default ({
	command,
	mode
}) => {
	const envConfig = loadEnv(mode, './');
	let config = {
		base: './',
		define: {
			'process.env': {}
		},
		//一下为新添加的内容
		resolve: {
			alias: {
				'~/': `${path.resolve(__dirname, 'src')}/`,
				'@/': `${path.resolve(__dirname, 'src')}/`,
			},
		},
		// 配置前端服务地址和端口
		server: {
			host: '0.0.0.0',
			headers: {
				"Access-Control-Allow-Origin": "*", //微应用本地开发，允许跨域
			},
			port: envConfig.VITE_VUE_APP_PORT,
			// 是否开启 https
			https: false,
			// 设置反向代理，跨域
			proxy: {
				'/api': {
					// 后台地址
					target: envConfig.VITE_VUE_APP_API_BASEURL,
					changeOrigin: true, //允许跨域
					ws: true, // 开启 websockets 代理
					secure: false, // 验证 SSL 证书
					rewrite: (path) => path.replace(/^\/api/, ""), // 重写传过来的path路径
				}
			},

		},
			// 强制预构建插件包
			optimizeDeps: {
				include: [
					`monaco-editor/esm/vs/language/json/json.worker`,
					`monaco-editor/esm/vs/language/css/css.worker`,
					`monaco-editor/esm/vs/language/html/html.worker`,
					`monaco-editor/esm/vs/language/typescript/ts.worker`,
					`monaco-editor/esm/vs/editor/editor.worker`
				],
			},

		css: {
			preprocessorOptions: {
				scss: {
					additionalData: `@use "~/style/style.scss" as *;`,
				},
			},
		},
		build: {
			cssCodeSplit: false,
			rollupOptions: {
				// 屏蔽不需要的语言
				output: {
					minifyInternalExports: true,
					manualChunks: (id, {
						getModuleInfo
					}) => {
						if (id.includes('node_modules')) {
							if (id.includes('axios')) {
								return 'axios'
							}
							if (id.includes('vue')) {
								return 'vue'
							}
							return 'vendor';
						} else if (id.includes('/src/')) {
							return 'app'
						}
					}
				},
			},
		

		},
		//
		plugins: [
			vue(),

			buildIndex(),
			AutoImport({
				resolvers: [ElementPlusResolver()],
			}),
			Components({
				resolvers: [ElementPlusResolver()],
			}),
			ElementPlus({
				useSource: true,
			}),
			createSvgIconsPlugin({
				iconDirs: [path.resolve(process.cwd(), 'src/assets'),path.resolve(process.cwd(), 'src/module/**/icon')],
				symbolId: 'dbant-icon-[name]',
				inject: 'body-first',
				customDomId: 'dbant_main__svg__icons__dom__'
			}),
		]
	};

	return defineConfig(config)
}
